package top.cyuw.subjectsystem.util;

import top.cyuw.subjectsystem.constant.JwtConstants;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Date;

public class JwtTokenUtils {

    public static String createToken(Integer userId, String userRole) {
        return Jwts.builder()
                .signWith(SignatureAlgorithm.HS512, JwtConstants.APPSECRET_KEY)
                .claim(JwtConstants.USER_ID, userId)
                .claim(JwtConstants.USER_ROLE, userRole)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + JwtConstants.EXPIRATION))
                .compact();
    }

    public static Integer getUserId(String token) {
        return (Integer) getTokenBody(token).get(JwtConstants.USER_ID);
    }

    public static Integer getUserId() {
        return getUserId(((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader(JwtConstants.HEADER_ACCESS_TOKEN));
    }

    public static String getUserRole(String token) {
        return (String) getTokenBody(token).get(JwtConstants.USER_ROLE);
    }

    public static String getUserRole() {
        return getUserRole(((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader(JwtConstants.HEADER_ACCESS_TOKEN));
    }

    private static Claims getTokenBody(String token) {
        return Jwts.parser().setSigningKey(JwtConstants.APPSECRET_KEY).parseClaimsJws(token).getBody();
    }

    public static boolean isExpiration(String token) {
        try {
            return getTokenBody(token).getExpiration().before(new Date());
        } catch (Exception e) {
            return true;
        }
    }

}

